import ddddocr
import re
import base64


class RegularCalculation:
    '''计算规则'''
    __div = re.compile(r"(\d+\.?\d*/-\d+\.?\d*)|(\d+\.?\d*/\d+\.?\d*)")  # 查找除法运算

    __mul = re.compile(r"(\d+\.?\d*\*-\d+\.?\d*)|(\d+\.?\d*\*\d+\.?\d*)")  # 查找乘法运算

    __add = re.compile(r"(-?\d+\.?\d*\+-\d+\.?\d*)|(-?\d+\.?\d*\+\d+\.?\d*)")  # 查找加法运算

    __sub = re.compile(r"(-?\d+\.?\d*--\d+\.?\d*)|(-?\d+\.?\d*-\d+\.?\d*)")  # 查找减法运算

    def division(self, value):
        """计算除法"""
        exp = re.split(r'/', self.__div.search(value).group())  # 将除法表达式拆分成列表
        return value.replace(self.__div.search(value).group(), str(float(exp[0]) / float(exp[1])))  # 计算并用结果替换列表中表达式

    def multiplication(self, value):
        """计算乘法"""
        exp = re.split(r'\*', self.__mul.search(value).group())  # 将乘法表达式拆分成列表
        return value.replace(self.__mul.search(value).group(), str(float(exp[0]) * float(exp[1])))  # 计算并用结果替换列表中表达式

    def addition(self, value):
        """计算加法"""
        exp = re.split(r'\+', self.__add.search(value).group())  # 将加法表达式拆分成列表
        return value.replace(self.__add.search(value).group(), str(float(exp[0]) + float(exp[1])))  # 计算并用结果替换列表中表达式

    def subtraction(self, value):
        """计算减法"""
        exp = self.__sub.search(value).group()  # 去除减法表达式
        if exp.startswith('-'):  # 如果表达式形如：-2.2-1.2；需变换为：-（2.2+1.2）
            exp = exp.replace('-', '+')  # 将-号替换为+号；+2.2+1.2
            res = self.addition(exp).replace('+', '-')  # 调用Add运算，将返回值+3.4变为-3.4
        else:
            exp = re.split(r'-', exp)
            res = str(float(exp[0]) - float(exp[1]))
        return value.replace(self.__sub.search(value).group(), res)


def recognize_from_base64(base64_str):
    '''处理base64验证码图片数据'''
    try:
        # 移除 Base64 头部（如果存在）
        if "," in base64_str:
            base64_data = base64_str.split(",")[1]
        else:
            base64_data = base64_str
        # 解码 Base64
        image_data = base64.b64decode(base64_data)
        return image_data
    except Exception as e:
        print(f"发生错误: {e}")
        return None


def verification_code(base64_str):
    ocr = ddddocr.DdddOcr()
    res = ocr.classification(recognize_from_base64(base64_str))
    print(res)
    try:
        if '+' in res:
            result = RegularCalculation().addition(res)
        elif '十' in res:
            result = RegularCalculation().addition(res.replace('十', '+'))
        elif '-' in res:
            result = RegularCalculation().subtraction(res)
        elif '一' in res:
            result = RegularCalculation().subtraction(res.replace('一', '-'))
        elif 'x' in res:
            result = RegularCalculation().multiplication(res.replace('x', '*'))
        else:
            result = RegularCalculation().division(res)
    except Exception as e:
        result = '计算出错'
        return result
    result = result.split('.')[0]
    return result


if __name__ == '__main__':
    base64_str = ""


    print(verification_code(base64_str))
